﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CdcSoftware.Pivotal.Applications.Core.Client;
using System.Data;
using CdcSoftware.Pivotal.Applications.Core.Common;
using CdcSoftware.Pivotal.Engine;
using CdcSoftware.Pivotal.Engine.Client.Services.Interfaces;
using Pcm.Retail.Client;
using System.Windows.Forms;
using CdcSoftware.Pivotal.Engine.UI.Forms;

namespace Pcm.Retail.Client.FormTasks
{
    public partial class RE_Batch : FormClientTask
    {
        #region Private Variables
        private bool changePassword = false;
        private bool clockOut = false;
        private Form popupAuthorization = null;
        private Form popupChangePassword = null;

        private System.Windows.Forms.TextBox txtCurrentPassword, txtNewPassword, txtConfirmPassword;
        private System.Windows.Forms.Button btnOk, btnCancel;
        private System.Windows.Forms.Label lblCurrentPassword, lblNewPassword, lblConfirmPassword;
        private bool passwordValidated = false;

        bool popUpShown = false;

        #endregion

        /// <summary>
        /// OnFormInitialized method call when a new form is opened.
        /// </summary>
        /// <history>
        /// Revision#      Date            Author          Description
        /// 6.0.9.1        2011-09-26      DS              Initial version for Retail.                                                
        /// </history>
        public override void OnFormInitialized()
        {
            try
            {
                base.OnFormInitialized();

                SharedLoad();
            }
            catch (Exception ex)
            {
                Globals.HandleException(ex, true);
            }
        }

        /// <summary>
        /// OnFormInitialized method call when a new form is opened.
        /// </summary>
        /// <history>
        /// Revision#      Date            Author          Description
        /// 6.0.9.1        2011-09-26      DS              Initial version for Retail.                                                
        /// </history>
        public override void OnFormReloaded()
        {
            try
            {
                
                base.OnFormReloaded();

                SharedLoad();
            }
            catch (Exception ex)
            {
                Globals.HandleException(ex, true);
            }
        }

        /// <summary>
        /// Method functionalities shared between OnFormInitialized and OnFormReloaded events.
        /// </summary>
        /// <history>
        /// Revision#      Date            Author          Description
        /// 6.0.9.1        2011-09-26      DS              Initial version for Retail.                                                
        /// </history>
        private void SharedLoad()
        {
            ((PivotalForeignKey)this.FormControl.GetControlByName("StoreId")).ReadOnly = true;

            //DS: 20052013 - Opening up the store target field for Manual fill-up,only when record is is null.
            //HD:05/Mar/2012:Start:Issue Fix 2: Store target to be mandatory and read-only on load/reload
            if (this.RecordId == null)
                ((PivotalNumber)this.FormControl.GetControlByName("StoreTarget")).ReadOnly = false;
            else
                ((PivotalNumber)this.FormControl.GetControlByName("StoreTarget")).ReadOnly = true;

            //RA:16/Aug/2012:Change for Mobile System:Start:
            bool masterPOS = false;
            Id storePOSId = Id.Create(Globals.ServerSqlIndex("Employee", "RE_Store_POS_Id", this.SystemClient.UserProfile.EmployeeId));

            if (storePOSId != null)
                masterPOS = TypeConvert.ToBoolean(Globals.ServerSqlIndex("RE_Store_POS", "Master_POS", storePOSId));
            //RA:16/Aug/2012:Change for Mobile System:End: 

            //Store target is populated from Re_Store_Target table
            if (this.RecordId == null)
            {
                if (!masterPOS)
                {
                    PivotalMessageBox.Show("Batch can only be created on the Master POS. Please try on the Terminal designated as Master POS.",
                            MessageBoxButtons.OK, MessageBoxIcon.Stop);
                    this.FormView.CloseForm(true);
                    return;
                }
                //RA:16/Aug/2012:Change for Mobile System:End:

                if (!Convert.IsDBNull(this.PrimaryDataRow["Store_Id"]))
                {
                    DataTable dtStoreTarget = Globals.GetDataTable("RE_Store Target for Today with Store?", new object[] { this.PrimaryDataRow["Store_Id"] },
                        "Store_Target", "RE_Store_Target_Id" );

                    if (dtStoreTarget != null && dtStoreTarget.Rows.Count > 0)
                    {
                        this.PrimaryDataRow["Store_Target"] = dtStoreTarget.Rows[0]["Store_Target"];
                        this.PrimaryDataRow["RE_Store_Target_Id"] = dtStoreTarget.Rows[0]["RE_Store_Target_Id"];
                    }
                }
                //Add Batch Cash Float rows to the secondary on Batch Creation.
                DataTable batchCashFloat = this.FormData.DataSet.Tables["RE_Batch_Cash_Float_Batch_Id"];
                base.NewSecondaryRecord("RE_Batch_Cash_Float_Batch_Id");
                DataRow batchCashFloatRow1 = batchCashFloat.Rows[batchCashFloat.Rows.Count - 1];
                batchCashFloatRow1["Cash_Float_Type"] = "Opening";
                base.NewSecondaryRecord("RE_Batch_Cash_Float_Batch_Id");
                DataRow batchCashFloatRow2 = batchCashFloat.Rows[batchCashFloat.Rows.Count - 1];
                batchCashFloatRow2["Cash_Float_Type"] = "Closing";
                //Disable the Actual Amount for the New Batch.
                EnableDisableDataGridCell("RE_Batch_Cash_Float_Batch_Id", "Actual_Amount", 1, false);
            }
            //HD:05/Mar/2012:End

            //RA:16/Aug/2012:Change for Mobile System:Start:
            //If LoggedInEmployee.POS.MasterPOS is False, the entire Batch form should be read-only including all the buttons.
            else
            {
                if (!masterPOS)
                    MakeBatchReadOnly();
            }
            //RA:16/Aug/2012:Change for Mobile System:End:           

            //If z_report_run Boolean is true, the entire batch form except the comments field should be read-only.
            //DS: z_report_run check is not required anymore.
            //if (TypeConvert.ToBoolean(this.PrimaryDataRow["Z_Report_Printed"]) || String.Equals(this.PrimaryDataRow["Batch_Status"].ToString(), "Closed"))
            if (String.Equals(this.PrimaryDataRow["Batch_Status"].ToString(), "Closed"))
            {
                Globals.EnableDisableAllPrimaryFields(false);
                Globals.EnableDisableAllSecondaries(false);
                ((PivotalTextBox)this.FormControl.GetControlByDataName("Comments")).Enabled = true;
                //Disable all the buttons.
                EnableDisableButtons(false);

                //DS: Keep the Print Report button enabled all the time.
                //if (String.Equals(this.PrimaryDataRow["Batch_Status"].ToString(), "Closed") && !TypeConvert.ToBoolean(this.PrimaryDataRow["Z_Report_Printed"]))
                //    ((PivotalButton)this.FormControl.GetControlByName("PivotalButton3")).Enabled = true;
                //else
                //    ((PivotalButton)this.FormControl.GetControlByName("PivotalButton3")).Enabled = false;
                ((PivotalButton)this.FormControl.GetControlByName("PivotalButton3")).Enabled = true;

                //Disable the secondary adds.
                EnableDisableSecondaryAddEdit(false);
            }
            else
            {
                if (masterPOS)
                {
                    Globals.EnableDisableAllPrimaryFields(true);
                    Globals.EnableDisableAllSecondaries(true);
                    Globals.EnableDisableSecondaryFields(false, "RE_Sale_Serial_Number_Batch_Id", "Product_Id__RE_SKU_Description");
                }

                if (this.RecordId == null)
                {
                    //RA:16/Aug/2012:Change for Mobile System:Start:
                    DataTable batch = Globals.GetDataTable("RE_In Progress Batch for Store for today?", new object[] { this.PrimaryDataRow["Store_Id"] }, "RE_Batch_Id");
                    //DataTable batch = Globals.GetDataTable("RE_In Progress Batch for Store?", new object[] { this.PrimaryDataRow["Store_Id"] }, "RE_Batch_Id");
                    //RA:16/Aug/2012:Change for Mobile System:End:

                    if (batch != null && batch.Rows.Count == 1)
                    {
                        PivotalMessageBox.Show("There is already a batch In Progress for this store.", MessageBoxButtons.OK, MessageBoxIcon.Information);

                        this.FormView.CloseForm(true);
                        Globals.ShowForm("RE_Batch", Id.Create(batch.Rows[0]["RE_Batch_Id"]));
                        return;
                    }
                    else if (batch != null && batch.Rows.Count > 1)
                    {
                        PivotalMessageBox.Show("Multiple batches are existing for this store with status In Progress. Please contact System Administrator.",
                            MessageBoxButtons.OK, MessageBoxIcon.Error);
                        this.FormView.CloseForm(true);
                        return;
                    }

                    //Populate Batch Details secondary with the corresponding values for each Tender_Type.
                    DataTable tenderType = Globals.GetDataTable("RE_All Tender Types", null, new string[] { "RE_Tender_Type_Id", "Tender_Type" });

                    if (tenderType != null && tenderType.Rows.Count > 0)
                    {
                        DataRow[] tenderTypeSorted = tenderType.Select(null, "Tender_Type");
                        foreach (DataRow dr in tenderTypeSorted)
                        {
                            if (!string.Equals(TypeConvert.ToString(dr["Tender_Type"]).ToUpper(), "CHANGE"))
                            {
                                DataRow batchDetailsRow = this.FormData.DataSet.Tables["RE_Batch_Detail_RE_Batch_Id"].NewRow();
                                batchDetailsRow["Tender_Type_Id"] = dr["RE_Tender_Type_Id"];
                                batchDetailsRow["Tender_Type_Id@Rn_Descriptor"] = dr["Tender_Type"];
                                //Done at form level.
                                batchDetailsRow["Opening_Amount"] = 0;
                                this.DataSet.Tables["RE_Batch_Detail_RE_Batch_Id"].Rows.Add(batchDetailsRow);
                            }
                        }
                    }
                    this.FormControl.GetControlByDataName("Opened_By_Id").Enabled = true;
                    EnableDisableDataGridCell("RE_Batch_Cash_Float_Batch_Id", "Remarks1", 0, true);
                    EnableDisableDataGridCell("RE_Batch_Cash_Float_Batch_Id", "Actual_Amount", 1, false);
                    EnableDisableDataGridCell("RE_Batch_Cash_Float_Batch_Id", "Remarks1", 1, false);
                }
                else
                    this.FormControl.GetControlByDataName("Opened_By_Id").Enabled = false;

                //Enable/Disable the buttons Run X AND Z.
                //Enable/Disable secondary Batch Details depending upon the status.
                if (String.Equals(this.PrimaryDataRow["Batch_Status"].ToString(), "In Progress") && this.RecordId != null)
                {
                    if (masterPOS)
                    {
                        EnableDisableButtons(true);
                        Globals.EnableDisableSecondary(false, "RE_Batch_Detail_RE_Batch_Id");

                        //Enable/Disable the Actual Amount for the Batch float type opening/closing.
                        EnableDisableDataGridCell("RE_Batch_Cash_Float_Batch_Id", "Actual_Amount", 0, false);
                        EnableDisableDataGridCell("RE_Batch_Cash_Float_Batch_Id", "Actual_Amount", 1, false);
                        EnableDisableDataGridCell("RE_Batch_Cash_Float_Batch_Id", "Remarks1", 0, false);
                        EnableDisableDataGridCell("RE_Batch_Cash_Float_Batch_Id", "Remarks1", 1, false);
                    }
                }
                else
                {
                    EnableDisableButtons(false);
                    Globals.EnableDisableSecondary(true, "RE_Batch_Detail_RE_Batch_Id");

                    //Set the batch details specific columns read-only.
                    Globals.EnableDisableSecondaryFields(false, "RE_Batch_Detail_RE_Batch_Id", new string[] { "Tender_Type_Id", "Batch_Sales", "Batch_CD_PO", 
                        "Expected_Amount", "Over_Short_Amount" });
                    //Globals.EnableDisableSecondaryFields(true, "RE_Batch_Detail_RE_Batch_Id", new string[] { "Remarks" });
                }

                //Enable the secondary adds.
                if (masterPOS)
                    EnableDisableSecondaryAddEdit(true);
            }
            Globals.EnableDisableSecondaryFields(false, "RE_Staff_Target_Batch_Id", new string[] { "Staff_Code", "Head_Count" });
            Globals.EnableDisableSecondaryFields(false, "RE_Batch_Cash_Float_Batch_Id", new string[] { "Cash_Float_Type", "Over_Short_Amount" });
            //DS: 21052013 - Make this Sale Serial Product Read-Only.
            Globals.EnableDisableSecondaryFields(false, "RE_Sale_Serial_Number_Batch_Id", "Product_Id");
            if (this.RecordId != null)
            {
                //DS:02112012 - when user opens a batch which is linked to store different from the logged in user's store,
                //the entire batch screen should be read-only
                //Get the logged-in users store details.
                if (!Id.Equals(Id.Create(this.PrimaryDataRow["Store_Id"]), Id.Create(Globals.ServerSqlIndex("Employee", "RE_Store_Id", this.SystemClient.UserProfile.EmployeeId))))
                    MakeBatchReadOnly();

                //DS: 20052013 - For Admin User, Enable the Print Report Button everytime.
                if (Globals.CurrentUserInSecurityGroup("Retail Administrator"))
                    ((PivotalButton)this.FormControl.GetControlByName("PivotalButton3")).Enabled = true;

                this.FormView.Dirty = false;
            }
        }

        /// <summary>
        /// Make the entire batch form read-only.
        /// </summary>
        private void MakeBatchReadOnly()
        {
            Globals.EnableDisableAllPrimaryFields(false);
            Globals.EnableDisableAllSecondaries(false);
            EnableDisableSecondaryAddEdit(false);
            EnableDisableButtons(false);
        }

        /// <summary>
        /// Disable a particular datagrid cell.
        /// </summary>
        /// <param name="secondaryName">Secondary Data Name</param>
        /// <param name="cellName">Cell name to be made read-only.</param>
        /// <param name="rowIndex">Row index for the cell.</param>
        /// <param name="enableCell">true, will enable the field for editing.</param>
        private static void EnableDisableDataGridCell(string secondaryName, string cellName, int rowIndex, bool enableCell)
        {
            IFormView formView = (IFormView)ClientContext.ClientAPIService.GetActiveContentObject();
            CdcSoftware.Pivotal.Engine.UI.Forms.PivotalClientFormControl formControl = (CdcSoftware.Pivotal.Engine.UI.Forms.PivotalClientFormControl)formView.FormControl;

            // Get the Secondary Segment into a PivotalSecondary object...
            CdcSoftware.Pivotal.Engine.UI.Forms.PivotalSecondary secondary = formControl.GetSecondary(secondaryName);

            if (secondary != null)
                secondary.Rows[rowIndex].Cells[cellName].ReadOnly = !enableCell;
        }

        /// <summary>
        /// Enable or Disable the form buttons.
        /// </summary>
        /// <param name="enableButtons">If true, then enable all the form Buttons else disable.</param>
        private void EnableDisableButtons(bool enableButtons)
        {
            ((PivotalButton)this.FormControl.GetControlByName("PivotalButton1")).Enabled = enableButtons;
            ((PivotalButton)this.FormControl.GetControlByName("PivotalButton2")).Enabled = enableButtons;
            ((PivotalButton)this.FormControl.GetControlByName("PivotalButton3")).Enabled = enableButtons;
        }

        /// <summary>
        /// Enable or Disable the form secondary add/edit buttons.
        /// </summary>
        /// <param name="enableSecondaryAddEdit">If true, then enable all the form secondary add/edit buttons, else disable.</param>
        private void EnableDisableSecondaryAddEdit(bool enableSecondaryAddEdit)
        {
            ((PivotalSecondary)this.FormControl.GetSecondary("RE_CashDrop_Payout_RE_Batch_Id")).AllowUserToAddRows = enableSecondaryAddEdit;
            ((PivotalSecondary)this.FormControl.GetSecondary("RE_CashDrop_Payout_RE_Batch_Id")).CanOpenRecords = enableSecondaryAddEdit;
            ((PivotalSecondary)this.FormControl.GetSecondary("RE_Staff_Target_Batch_Id")).AllowUserToAddRows = enableSecondaryAddEdit;
        }

        /// <summary>
        /// Verify if any cashier is logged-in or not and set the field Closed_By_Id. If cashier is not in, then redirect to the cashier login/logout form.
        /// </summary>
        /// <returns>true, if there is a cashier logged-in and false otherwise</returns>
        private bool VerifyCashierLogin()
        {
            bool isCashierIn = false;

            //Added Code to check Cashier_Log for today. If no Cashier found prompt message and close the RE_Sale Walk-in form.
            DataTable cashierLog = Globals.GetDataTable("RE_All Cashier Logins for Today where EndTime is Null with POS ?",
                    new object[] { this.PrimaryDataRow["RE_POS_Id"] }, "Staff_Id");

            //One Cashier logged in
            if (cashierLog != null && cashierLog.Rows.Count == 1)
            {
                //Set the Closed_By_Id field.
                this.PrimaryDataRow["Closed_By_Id"] = cashierLog.Rows[0]["Staff_Id"];
                return true;
            }
            if (cashierLog != null && cashierLog.Rows.Count == 0)
            {
                PivotalMessageBox.Show("No Cashier found logged in to the POS.", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                this.FormView.CloseForm(true);
                Globals.NewForm("RE_Cashier_Log", null);
                isCashierIn = false;
            }
            else if (cashierLog != null && cashierLog.Rows.Count > 1)
            {
                PivotalMessageBox.Show("Multiple Cashiers are found logged in to the POS. Please contact the Administrator.", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                this.PrimaryDataRow["Closed_By_Id"] = DBNull.Value;
                isCashierIn = false;
            }
            return isCashierIn;
        }

        /// <summary>
        /// Saves the record.
        /// </summary>
        /// <history>
        /// Revision#      Date            Author          Description
        /// 6.0.9.1        2011-09-27      DS              Initial version for Retail.                                                
        /// </history>
        public override bool SaveRecord()
        {
            try
            {
                if (String.Equals(this.PrimaryDataRow["Batch_Status"].ToString(), "Open"))
                {
                    //that the batch will not be in use unless the status is changed to “In Progress”
                    PivotalMessageBox.Show("The batch will not be in use unless the status is changed to In Progress",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
                    //DS: 21-06-2012 Opening Amount is not necessary anymore.
                    //if (this.RecordId == null)
                    //{
                    //    if (PivotalMessageBox.Show("Please ensure the Opening Amounts are filled in in the Details section. Click OK to save the form, else click Cancel.",
                    //        MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.Cancel)
                    //        return false;
                    //}
                }
                //DS: 21-06-2012 Opening Amount is not necessary anymore.
                //else if (this.RecordId == null && String.Equals(this.PrimaryDataRow["Batch_Status"].ToString(), "In Progress"))
                //{
                //    if (PivotalMessageBox.Show("Please ensure the opening amounts are filled in in the Details section. Click OK to save the form and proceed, else click Cancel.",
                //        MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.Cancel)
                //        return false;
                //}
                else if (String.Equals(this.PrimaryDataRow["Batch_Status"].ToString(), "Closed"))
                {
                    if (this.RecordId != null && SystemClient.SystemInformation.IsMobile)
                    {
                        PivotalMessageBox.Show("Batch can only be closed in online mode.", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return false;
                    }
                    else if (this.RecordId != null && VerifyCashierLogin())
                        return SharedRunXandZ(false, true);
                }
                if (TypeConvert.ToDouble(this.PrimaryDataRow["Total_Staff_Target"]) > TypeConvert.ToDouble(this.PrimaryDataRow["Store_Target"]))
                {
                    PivotalMessageBox.Show("Sum of the individual Staff Targets exceed Store Target. Please correct and save again.",
                        MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
                    return false;
                }

                if (this.RecordId == null)
                {
                    if (Convert.IsDBNull(this.DataSet.Tables["RE_Batch_Cash_Float_Batch_Id"].Rows[0]["Actual_Amount"])
                        || (this.DataSet.Tables["RE_Batch_Cash_Float_Batch_Id"].Rows[0]["Actual_Amount"] == null))
                    {
                        PivotalMessageBox.Show("Actual amount is mandatory for Cash Float type 'Opening' in a new Batch.", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return false;
                    }

                    if (TypeConvert.ToDouble(this.DataSet.Tables["RE_Batch_Cash_Float_Batch_Id"].Rows[0]["Over_Short_Amount"]) != 0 
                        && String.IsNullOrWhiteSpace(this.DataSet.Tables["RE_Batch_Cash_Float_Batch_Id"].Rows[0]["Remarks"].ToString()))
                    {
                        PivotalMessageBox.Show("Remarks is mandatory corresponding to Cash Float type 'Opening', where Over/Short Amount is not zero.",
                            MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return false;
                    }
                }

                bool saveRecord = base.SaveRecord();
                //NN 05 March 2012:Issue No. 88
                //Displaying a Message for user if Warning Message is returned for Batch server Task.
                if (!String.IsNullOrEmpty(this.TransitionPointParameter.WarningMessage))
                    PivotalMessageBox.Show("There is already a batch In Progress for this store.", MessageBoxButtons.OK, MessageBoxIcon.Information);

                return saveRecord;
            }
            catch (Exception ex)
            {
                Globals.HandleException(ex, true);
            }
            return false;
        }

        /// <summary>
        /// Event handler for the OK click of the popup pwd challenge.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <history>
        /// Revision#      Date            Author          Description
        /// 6.0.8.1        2011-09-06      DS              Initial version for Retail.                                                
        /// </history>
        private void Ok_Click(object sender, EventArgs e)
        {
            try
            {
                if (changePassword)
                {
                    //Verify the current password is correct and the new password matches the confirm password fields.
                    //Update the new password in the staff table and clear the Prompt_To_Change field and Clock-In the staff.

                    //User selects OK but value not provided.
                    if (txtCurrentPassword.Text.Trim() == string.Empty || txtNewPassword.Text.Trim() == string.Empty || txtConfirmPassword.Text.Trim() == string.Empty)
                    {
                        this.txtCurrentPassword.Text = string.Empty;
                        this.txtNewPassword.Text = string.Empty;
                        this.txtConfirmPassword.Text = string.Empty;
                        this.txtCurrentPassword.Focus();
                        return;
                    }

                    string password = TypeConvert.ToString(Globals.ServerSqlIndex("RE_Staff", "Password_", Id.Create(this.PrimaryDataRow["Opened_By_Id"])));
                    //Match the old password with the DB value. If matched go ahead, esle prompt the user.
                    if (String.Equals(Globals.Decrypt(password), txtCurrentPassword.Text))
                    {
                        //If new password and the confirm password does not match prompt the user with error.
                        if (!String.Equals(txtNewPassword.Text, txtConfirmPassword.Text))
                        {
                            PivotalMessageBox.Show("Password confirmation failed. Please enter again.", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            this.txtNewPassword.Text = string.Empty;
                            this.txtConfirmPassword.Text = string.Empty;
                            this.txtNewPassword.Focus();
                            return;
                        }

                        //Now change the password for the Staff and set the field Prompt_To_Reset to false.
                        this.SystemClient.ExecuteServerTask("RE_Store", "SetStaffPassword", new Type[] { typeof(Id), typeof(string) },
                            new object[] { Id.Create(this.PrimaryDataRow["Opened_By_Id"]), Globals.Encrypt(this.txtNewPassword.Text) });

                        //After successful validation and password change, close the pop-up.
                        popupChangePassword.Close();

                        passwordValidated = true;
                    }
                    else
                    {
                        PivotalMessageBox.Show("Current Password verification failed. Please enter again.", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        this.txtCurrentPassword.Text = string.Empty;
                        this.txtNewPassword.Text = string.Empty;
                        this.txtConfirmPassword.Text = string.Empty;
                        this.txtCurrentPassword.Focus();
                        return;
                    }
                }
                else
                {
                    //Verify the current password is correct and clock in the staff.
                    //User selects OK but value not provided.
                    if (txtCurrentPassword.Text.Trim() == string.Empty)
                    {
                        this.txtCurrentPassword.Text = string.Empty;
                        this.txtCurrentPassword.Focus();
                        return;
                    }

                    string password = TypeConvert.ToString(Globals.ServerSqlIndex("RE_Staff", "Password_", Id.Create(this.PrimaryDataRow["Opened_By_Id"])));
                    //Match the password with the DB value. If matched go ahead, esle prompt the user.
                    if (String.Equals(Globals.Decrypt(password), txtCurrentPassword.Text))
                    {
                        //After successful validation and password change, close the pop-up.
                        popupAuthorization.Close();
                    }
                    else
                    {
                        PivotalMessageBox.Show("Password verification failed. Please enter again.", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        this.txtCurrentPassword.Text = string.Empty;
                        this.txtCurrentPassword.Focus();
                        return;
                    }

                    passwordValidated = true;
                }
            }
            catch (Exception ex)
            {
                Globals.HandleException(ex, true);
            }
        }

        /// <summary>
        /// Shows the Authorization Prompt.
        /// </summary>
        private void ShowAuthorizationPopup()
        {
            changePassword = false;
            popupAuthorization = new Form();

            this.txtCurrentPassword = new System.Windows.Forms.TextBox();
            this.btnOk = new System.Windows.Forms.Button();
            this.btnCancel = new System.Windows.Forms.Button();
            this.lblCurrentPassword = new System.Windows.Forms.Label();
            popupAuthorization.SuspendLayout();
            // 
            // txtCurrentPassword
            // 
            this.txtCurrentPassword.Location = new System.Drawing.Point(181, 30);
            this.txtCurrentPassword.Name = "txtCurrentPassword";
            this.txtCurrentPassword.Size = new System.Drawing.Size(109, 20);
            this.txtCurrentPassword.TabIndex = 1;
            this.txtCurrentPassword.UseSystemPasswordChar = true;
            // 
            // btnOk
            // 
            this.btnOk.Location = new System.Drawing.Point(134, 80);
            this.btnOk.Name = "Ok";
            this.btnOk.Size = new System.Drawing.Size(75, 23);
            this.btnOk.TabIndex = 2;
            this.btnOk.Text = "Ok";
            this.btnOk.UseVisualStyleBackColor = true;
            this.btnOk.Click += new System.EventHandler(this.Ok_Click);
            // 
            // btnCancel
            // 
            this.btnCancel.Location = new System.Drawing.Point(215, 80);
            this.btnCancel.Name = "Cancel";
            this.btnCancel.Size = new System.Drawing.Size(75, 23);
            this.btnCancel.TabIndex = 3;
            this.btnCancel.Text = "Cancel";
            this.btnCancel.UseVisualStyleBackColor = true;
            // 
            // lblCurrentPassword
            // 
            this.lblCurrentPassword.AutoSize = true;
            this.lblCurrentPassword.Location = new System.Drawing.Point(43, 33);
            this.lblCurrentPassword.Name = "lblCurrentPassword";
            this.lblCurrentPassword.Size = new System.Drawing.Size(138, 15);
            this.lblCurrentPassword.TabIndex = 5;
            this.lblCurrentPassword.Text = "Password:";
            // 
            // Form1
            // 
            popupAuthorization.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            popupAuthorization.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            popupAuthorization.AcceptButton = this.btnOk;
            popupAuthorization.CancelButton = this.btnCancel;
            popupAuthorization.ClientSize = new System.Drawing.Size(348, 133);
            popupAuthorization.StartPosition = FormStartPosition.CenterScreen;
            popupAuthorization.Controls.Add(this.lblCurrentPassword);
            popupAuthorization.Controls.Add(this.btnOk);
            popupAuthorization.Controls.Add(this.btnCancel);
            popupAuthorization.Controls.Add(this.txtCurrentPassword);
            popupAuthorization.Name = "popupAuthorization";
            popupAuthorization.Text = "Enter Password";
            popupAuthorization.ResumeLayout(false);
            popupAuthorization.PerformLayout();
            popupAuthorization.ShowDialog();
        }

        /// <summary>
        /// Show the Change password prompt..
        /// </summary>
        /// <history>
        /// Revision#      Date            Author          Description
        /// 6.0.12.1       15032013        DS              Initial version for Retail.                                                
        /// </history>
        private void ShowChangePasswordPopup()
        {
            changePassword = true;
            popupChangePassword = new Form();

            this.txtCurrentPassword = new System.Windows.Forms.TextBox();
            this.txtNewPassword = new System.Windows.Forms.TextBox();
            this.txtConfirmPassword = new System.Windows.Forms.TextBox();
            this.btnOk = new System.Windows.Forms.Button();
            this.btnCancel = new System.Windows.Forms.Button();
            this.lblCurrentPassword = new System.Windows.Forms.Label();
            this.lblNewPassword = new System.Windows.Forms.Label();
            this.lblConfirmPassword = new System.Windows.Forms.Label();
            popupChangePassword.SuspendLayout();
            // 
            // txtCurrentPassword
            // 
            this.txtCurrentPassword.Location = new System.Drawing.Point(181, 30);
            this.txtCurrentPassword.Name = "txtCurrentPassword";
            this.txtCurrentPassword.Size = new System.Drawing.Size(109, 20);
            this.txtCurrentPassword.TabIndex = 0;
            this.txtCurrentPassword.UseSystemPasswordChar = true;
            // 
            // txtNewPassword
            // 
            this.txtNewPassword.Location = new System.Drawing.Point(181, 71);
            this.txtNewPassword.Name = "txtNewPassword";
            this.txtNewPassword.Size = new System.Drawing.Size(109, 20);
            this.txtNewPassword.TabIndex = 1;
            this.txtNewPassword.UseSystemPasswordChar = true;
            // 
            // txtConfirmPassword
            // 
            this.txtConfirmPassword.Location = new System.Drawing.Point(181, 112);
            this.txtConfirmPassword.Name = "txtNewPassword";
            this.txtConfirmPassword.Size = new System.Drawing.Size(109, 20);
            this.txtConfirmPassword.TabIndex = 2;
            this.txtConfirmPassword.UseSystemPasswordChar = true;
            // 
            // btnOk
            // 
            this.btnOk.Location = new System.Drawing.Point(134, 161);
            this.btnOk.Name = "Ok";
            this.btnOk.Size = new System.Drawing.Size(75, 23);
            this.btnOk.TabIndex = 3;
            this.btnOk.Text = "Ok";
            this.btnOk.BringToFront();
            this.btnOk.UseVisualStyleBackColor = true;
            this.btnOk.Click += new System.EventHandler(this.Ok_Click);
            // 
            // btnCancel
            // 
            this.btnCancel.Location = new System.Drawing.Point(215, 161);
            this.btnCancel.Name = "Cancel";
            this.btnCancel.Size = new System.Drawing.Size(75, 23);
            this.btnCancel.TabIndex = 4;
            this.btnCancel.Text = "Cancel";
            this.btnCancel.UseVisualStyleBackColor = true;
            // 
            // lblCurrentPassword
            // 
            this.lblCurrentPassword.AutoSize = true;
            this.lblCurrentPassword.Location = new System.Drawing.Point(43, 33);
            this.lblCurrentPassword.Name = "lblCurrentPassword";
            this.lblCurrentPassword.Size = new System.Drawing.Size(138, 15);
            this.lblCurrentPassword.TabIndex = 5;
            this.lblCurrentPassword.Text = "Current Password:";
            // 
            // lblNewPassword
            // 
            this.lblNewPassword.AutoSize = true;
            this.lblNewPassword.Location = new System.Drawing.Point(43, 74);
            this.lblNewPassword.Name = "lblNewPassword";
            this.lblNewPassword.Size = new System.Drawing.Size(138, 15);
            this.lblNewPassword.TabIndex = 5;
            this.lblNewPassword.Text = "New Password:";
            // 
            // lblConfirmPassword
            // 
            this.lblConfirmPassword.AutoSize = true;
            this.lblConfirmPassword.Location = new System.Drawing.Point(43, 115);
            this.lblConfirmPassword.Name = "lblConfirmPassword";
            this.lblConfirmPassword.Size = new System.Drawing.Size(138, 15);
            this.lblConfirmPassword.TabIndex = 6;
            this.lblConfirmPassword.Text = "Confirm Password:";
            // 
            // Form1
            // 
            popupChangePassword.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            popupChangePassword.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            popupChangePassword.AcceptButton = this.btnOk;
            popupChangePassword.CancelButton = this.btnCancel;
            popupChangePassword.ClientSize = new System.Drawing.Size(348, 224);
            popupChangePassword.StartPosition = FormStartPosition.CenterScreen;
            popupChangePassword.Controls.Add(this.lblCurrentPassword);
            popupChangePassword.Controls.Add(this.lblNewPassword);
            popupChangePassword.Controls.Add(this.lblConfirmPassword);
            popupChangePassword.Controls.Add(this.btnOk);
            popupChangePassword.Controls.Add(this.btnCancel);
            popupChangePassword.Controls.Add(this.txtCurrentPassword);
            popupChangePassword.Controls.Add(this.txtNewPassword);
            popupChangePassword.Controls.Add(this.txtConfirmPassword);
            popupChangePassword.Name = "popupChangePassword";
            popupChangePassword.Text = "Change Password";
            popupChangePassword.ResumeLayout(false);
            popupChangePassword.PerformLayout();
            popupChangePassword.ShowDialog();
        }

        /// <summary>
        /// Set focus on the next secondary cell .
        /// </summary>
        /// <param name="Sender"></param>
        /// <param name="args"></param>
        private void SetFocusOnSecondaryCell(DataGridView Sender, string columnName, int rowIndex)
        {
            Sender.Focus();
            Sender.CurrentCell = Sender[columnName, rowIndex];
            Sender.BeginEdit(true);
        }
    }
}
